package com.example.homemate.controller.owner;

import com.example.homemate.model.entity.owner.Owner;
import com.example.homemate.service.owner.OwnerService;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/owners")
@CrossOrigin(origins = "http://localhost:5173")
public class OwnerController {

    private final OwnerService ownerService;

    public OwnerController(OwnerService ownerService) {
        this.ownerService = ownerService;
        System.out.println("OwnerController 实行00001");
    }

    @GetMapping
    public ResponseEntity<Page<Owner>> getOwners(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sortField,
            @RequestParam(defaultValue = "asc") String sortDirection
    ) {
        // 简单的边界检查
        if (page <= 0) page = 1;
        if (size <= 0) size = 10;

        Page<Owner> owners = ownerService.getOwners(page, size, sortField, sortDirection);
        System.out.println("业主信息列表：");
        for (Owner owner : owners.getContent()) {
            System.out.println("业主ID: " + owner.getId() + ", 姓名: " + owner.getName());
        }
        return ResponseEntity.ok(owners);
    }

    @PostMapping
    public ResponseEntity<Owner> createOwner(@RequestBody Owner owner) {
        Owner savedOwner = ownerService.saveOwner(owner);
        return new ResponseEntity<>(savedOwner, HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Owner> updateOwner(@PathVariable Long id, @RequestBody Owner owner) {
        Owner updatedOwner = ownerService.updateOwner(id, owner);
        return ResponseEntity.ok(updatedOwner);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOwner(@PathVariable Long id) {
        ownerService.deleteOwner(id);
        return ResponseEntity.noContent().build();
    }
}